package com.htd.htdapmservice.rabbitListener;

import com.htd.htdapmcommon.constants.AlarmConstants;
import com.htd.htdapmdmo.AlarmsInfo;
import com.htd.htdapmservice.dao.AlarmsInfoDao;
import com.htd.htdapmservice.result.ResponseAlarmInfo;
import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Component
@RabbitListener(queues = "cloudAlertFeedback.queue")
public class CloudAlertFeedbackListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(CloudAlertFeedbackListener.class);

    @Resource
    private TransportClient client;

    @Autowired
    private AlarmsInfoDao alarmsInfoDao;

    @RabbitHandler
    public void process(ResponseAlarmInfo responseAlarmInfo){
        try{
            List<AlarmsInfo> alarmsInfoList = alarmsInfoDao.getInfoByAlarmsId(responseAlarmInfo.getEventId());

            if(CollectionUtils.isNotEmpty(alarmsInfoList)){

                for (AlarmsInfo alarmsInfo:alarmsInfoList) {
                    // 1、更新ES
                    boolean b = updateAlarm(alarmsInfo.getAlarmsId(), responseAlarmInfo.getStatus(), alarmsInfo.getAlarmsProductTypeCode());
                    if(!b){
                        LOGGER.info("updateAlarmStatus更新es状态失败,alarmsId为{}", responseAlarmInfo.getEventId());
                    }
                    // 2、更新数据库
                    HashMap<String, Object> params = new HashMap<String, Object>();
                    params.put("alarmsStatus", responseAlarmInfo.getStatus());
                    params.put("id", alarmsInfo.getId());
                    alarmsInfoDao.updateAlarmsStatusById(params);
                }
            }
        } catch (Exception e) {
            LOGGER.error("更新状态异常,", e);
        }
    }

    public boolean updateAlarm(String alarmId, String alarmStatus,String productCode) {
        LOGGER.info("告警ID为:{},告警状态:{}", alarmId, alarmStatus);
        try {
            UpdateResponse updateResponse = new UpdateResponse();
            GetResponse getResponse = null;
            UpdateRequest request = null;

            if(AlarmConstants.TYPE_SKYWALKING.equalsIgnoreCase(productCode)){
                getResponse = getES(AlarmConstants.SKYWALKING_INDEX_NAME, AlarmConstants.SKYWALKING_TYPE_NAME, alarmId);
                request = getUpdateRequest(getResponse,AlarmConstants.SKYWALKING_INDEX_NAME, AlarmConstants.SKYWALKING_TYPE_NAME, alarmId);
            }else if(AlarmConstants.TYPE_PROMETHEUS.equalsIgnoreCase(productCode)){
                getResponse = getES(AlarmConstants.PROMETHEUS_INDEX_NAME, AlarmConstants.PROMETHEUS_TYPE_NAME, alarmId);
                request = getUpdateRequest(getResponse,AlarmConstants.PROMETHEUS_INDEX_NAME, AlarmConstants.PROMETHEUS_TYPE_NAME, alarmId);
            } else if(AlarmConstants.TYPE_ZABBIX.equalsIgnoreCase(productCode)){
                getResponse = getES(AlarmConstants.ZABBIX_INDEX_NAME, AlarmConstants.ZABBIX_TYPE_NAME, alarmId);
                request = getUpdateRequest(getResponse,AlarmConstants.ZABBIX_INDEX_NAME, AlarmConstants.ZABBIX_TYPE_NAME, alarmId);
            }else{
                getResponse = getES(AlarmConstants.BUSINESS_INDEX_NAME, AlarmConstants.BUSINESS_TYPE_NAME, alarmId);
                request = getUpdateRequest(getResponse,AlarmConstants.BUSINESS_INDEX_NAME, AlarmConstants.BUSINESS_TYPE_NAME, alarmId);
            }

            if(request==null){
                return true;
            }
            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
            if (alarmStatus != null) {
                builder.field("alarmStatus", alarmStatus);
            }
            builder.endObject();
            request.doc(builder);
            updateResponse = client.update(request).get();
            LOGGER.info("更新ES结果:{}",updateResponse.getResult());
        } catch (Exception e) {
            LOGGER.error("更新告警数据失败:", e);
            return false;
        }
        return true;
    }

    //获取ES 告警数据
    private GetResponse getES( String alarmIndex,String alarmType,String alarmId){
        GetResponse getResponse = client.prepareGet(alarmIndex,alarmType, alarmId).execute().actionGet();
        return getResponse;
    }

    private UpdateRequest getUpdateRequest(GetResponse getResponse,String alarmIndex,String alarmType,String alarmId){
        UpdateRequest updateRequest = null;
        if(getResponse != null && getResponse.isExists()){
            updateRequest = new UpdateRequest(alarmIndex, alarmType, alarmId);
        }
        return updateRequest;
    }
}
